//应收结算

/**
 * 应收结算列表视图
 */
interface ReceivableCloseViewModel extends IBaseViewModel<ReceivableCloseQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<FinanceReceivableListItemResponse>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     *查询
     */
    query: () => void;
    /**
     *客户单位
     */
    clientName: string;
    /**
     *结算单位
     */
    settle: string;
    /**
     *商务专员
     */
    businessaffairsid: string;
    /**
     *合同号
     */
    contractnumber: string;
    /**
     *车牌号
     */
    carcode: string;
    /**
     *发货起始时间
     */
    starttime: string;
    /**
     *发货结束时间
     */
    endtime: string;
    /**
     *回单状态
     */
    receiptstatus: string;
    /**
     *结算状态
     */
    settlestatus: string;
    /**
     *发货地址
     */
    origin: string;
    /**
     *送货地址
     */
    destination: string;
    /**
     *应收费用类型
     */
    feeType: string;
    /**
     *订单状态
     */
    orderStatus: string;
    /**
     * 商务专员下拉
     */
    businessOfficerList: EmployeeListItemResponse[];
    /**
     * 回单状态下拉
     */
    receiptPriceStatusList: ValueListItemResponse[];
    /**
     * 结算状态下拉
     */
    settleTypeList: ValueListItemResponse[];
    /**
     * 应收费用类型下拉
     */
    feeTypeList: ValueListItemResponse[];
    /**
     * 订单状态下拉
     */
    orderStatusList: ValueListItemResponse[];
    /**
     * 审核权限
     */
    isauthAudit: boolean;
    /**
     * 应收账单权限
     */
    isauthBill: boolean;
    /**
     * 导出报表
     */
    isauthExpect: boolean;
    /**
     * 记录选中编号值，在重新查询后会清除
     */
    receivableIdList: any;
    /**
     * 应收合计
     */
    totalReceivable: number;
    /**
     * 应收对账跳转
     */
    receivableEdit: (CarrierOrderId: string, OrderId: string, OrderChildId: string, id: string, settleStatus: string, totalPrice: string, price: string, unit: string, receivableCode: string) => void;
    /**
     *应收对账跳转
     */
    empty: () => void;
    /**
    * 审核退回
    */
    auditBack: () => void;
    /**
    * 审核通过
    */
    auditPass: () => void;
    /**
    *生成应收账单
    */
    receivableChecking: () => void;
    /**
    *新增应收单
    */
    receivableAdd: () => void;
    /**
    *取消审核
    */
    cancel: (id: string) => void
    /**
    *报表
    */
    skipExcel: () => void
    /**
    *导出
    */
    excel: () => void
    /**
    *删除选中订单
    */
    delId: (arg: any) => void;

    /**
     * 列表高度
     */
    heightA:number
}


/**
 * 查询条件
 */
interface ReceivableCloseQueryTerms {
    /**
     *客户单位
     */
    clientName: string;
    /**
     *结算单位
     */
    settle: string;
    /**
     *商务专员
     */
    businessaffairsid: string;
    /**
     *合同号
     */
    contractnumber: string;
    /**
     *车牌号
     */
    carcode: string;
    /**
     *发货起始时间
     */
    starttime: string;
    /**
     *发货结束时间
     */
    endtime: string;
    /**
     *回单状态
     */
    receiptstatus: string;
    /**
     *结算状态
     */
    settlestatus: string;
    /**
     *发货地址
     */
    origin: string;
    /**
     *送货地址
     */
    destination: string;
    /**
     *应收费用类型
     */
    feeType: string;
    /**
     *订单状态
     */
    orderStatus: string;

    /**
     * 18-3-1 新增：实际发货起始时间
     */
    realStartTime:string;
    /**
     * 18-3-1 新增：实际发货结束时间
     */
    realEndTime:string;
}


class ReceivableCloseController extends ListController<ReceivableCloseViewModel, ReceivableCloseQueryTerms>{
    gridApi: uiGrid.IGridApiOf<FinanceReceivableListItemResponse>;
    /**
     * 排序字段枚举
     */
    orderBy: number = 0;
    /**
     * 是否升序
     */
    asc: boolean = true;
    /**
     * 结算单id
     */
    settleid: string = "";
    /**
     * 应收总单编号
     */
    parentid: string = "";
    /**
     *是否为未结账应收 
     */
    isaccountenroute: boolean = null;
    /**
     * 应收编号
     */
    receivablecode: string = "";
    /**
     * 选定选中，防止在翻页恢复选中效果时候误操作
     */
    lockSelect: boolean;



    constructor($scope: ReceivableCloseViewModel,
        private receivableService: IReceivableService,
        private valueService: IValueService,
        private orderService: IorderService,
        private $ngBootbox: BootboxService,
        private $state: angular.ui.IStateService,
        private authorizationService: IAuthorizationService,
        private employeeService: IEmployeeService,
        private $timeout: ng.ITimeoutService,
        private exportService:IexportService,
        private $http: ng.IHttpService,
        private $location:ng.ILocationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();

        this.$scope.queryTerms = {
            clientName:"",
            settle: "",
            businessaffairsid: "",
            contractnumber: "",
            carcode:"",
            starttime:"",
            endtime:"",
            receiptstatus:"",
            settlestatus:"1",
            origin:"",
            destination:"",
            feeType:"",
            orderStatus:"",
            realStartTime:"",
            realEndTime:""
        }

        this.loadValueDropDown();
        this.loadBusinessOfficerDropDown();

        this.$scope.receivableEdit = this.receivableEdit;
        this.$scope.empty = this.empty;
        this.$scope.auditBack = this.auditBack;
        this.$scope.auditPass = this.auditPass;
        this.$scope.receivableChecking = this.receivableChecking;
        this.$scope.receivableAdd = this.receivableAdd;
        this.$scope.cancel = this.cancel;
        // this.$scope.skipExcel = this.excel;
        this.$scope.delId = (id)=>{this.delId(id,this.$scope.gridOptions.data)};

        this.lockSelect = false;
        this.$scope.receivableIdList = [];

        this.$scope.isauthAudit = false;
        this.$scope.isauthBill = false;
        this.$scope.isauthExpect = false;
        this.authorizationService.auth("25B5C4744B62B2487505ED240CCADD8443A4C94ED9C4394C26ACAC283E7C2B9D").then((res) => {
            this.$scope.isauthAudit = res.data.extData || true;
        }, (rej) => { });

        this.authorizationService.auth("25B5C4744B62B2487505ED240CCADD8443A4C94ED9C4394C9B49B21F33CCB59D").then((res) => {
            this.$scope.isauthBill = res.data.extData || true;
        }, (rej) => { });

        this.authorizationService.auth("25B5C4744B62B248E85CFABA3575091FED9E4CEEF454ABCC548010E996D7BE3F1D3BFDE595984B7E").then((res) => {
            this.$scope.isauthExpect = res.data.extData || true;
        }, (rej) => { });


        /*datetimepicker*/
        $('#openstarttime').click(function () {
            $('#starttime').datetimepicker('show');
        });
        $('#openendtime').click(function () {
            $('#endtime').datetimepicker('show');
        });

        $('#openRealStarttime').click(function () {
            $('#realStarttime').datetimepicker('show');
        });
        $('#openRealEndtime').click(function () {
            $('#realEndtime').datetimepicker('show');
        });



         this.paginationOptions= {
            skipSize:0,            
            pageSize: 50,
            currentPage: 1,   
        };
        this.$scope.gridOptions = {
            enableSelectAll: true,//全选禁用
            
            paginationPageSizes: [50, 80, 100],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            enableFullRowSelection: true,
            multiSelect: true,
            columnDefs: [
                {
                    displayName: "应收编号", field: 'receivableCode', enableColumnMenu: false, width: '9%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: "应收费用类型", field: 'feeType', enableColumnMenu: false, width: '6%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '结算单位', field: 'settle', enableColumnMenu: false, width: '9%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '发货地址', field: 'originAddress', enableColumnMenu: false, width: '9%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '送货地址', field: 'destinationAddress', enableColumnMenu: false, width: '9%', enableSorting: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '发货日期', field: 'realDeliveryTime', enableColumnMenu: false, width: '7%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '货物名称', field: 'goodsName', enableColumnMenu: false, width: '9%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '货物数量', field: 'quantityOfGoods', enableColumnMenu: false, enableSorting: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '应收单价', field: 'receivablePrice', enableColumnMenu: false, enableSorting: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '应收总价', field: 'receivableTotalPrice', enableColumnMenu: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: "应收说明", field: 'receivableSummary', enableColumnMenu: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '车牌号', field: 'carCode', enableColumnMenu: false, width: '6%', cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '合同号', field: 'contractNumber', enableColumnMenu: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '订单状态', field: 'orderStatus', enableColumnMenu: false, enableSorting: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '结算状态', field: 'settleStatus', enableColumnMenu: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: '回单状态', field: 'receiptStatus', enableColumnMenu: false, cellTooltip:
                    true, headerTooltip: true,
                },
                {
                    displayName: "操作",
                    field: 'orderStatus',
                    cellTemplate: '<div ng-if="row.entity.settleStatus ==\'已审核\' ">'
                    + '<a class="fa fa-edit m-l-xs  primary text-info" title="应收对账" ng-click="grid.appScope.receivableEdit(row.entity.carrierOrderId,row.entity.orderId,row.entity.orderChildId,row.entity.id,row.entity.settleStatus,row.entity.receivableTotalPrice,row.entity.receivablePriceStr,row.entity.receivablePriceUnit,row.entity.receivableCode)" ></a> &nbsp'
                    + '<a class="fa fa-minus-circle primary text-primary " title="取消审核" ng-click="grid.appScope.cancel(row.entity.id)" ></a>'
                    + '</div>'
                    + '<div ng-if="row.entity.settleStatus !=\'已审核\' ">'
                    + '<a class="fa fa-edit m-l-xs  primary text-info" title="应收对账" ng-click="grid.appScope.receivableEdit(row.entity.carrierOrderId,row.entity.orderId,row.entity.orderChildId,row.entity.id,row.entity.settleStatus,row.entity.receivableTotalPrice,row.entity.receivablePriceStr,row.entity.receivablePriceUnit,row.entity.receivableCode)" ></a>'
                    + '</div>', enableColumnMenu: false, enableSorting: false

                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.core.notifyDataChange("options");
                // gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                //     this.paginationChanged(skipSize,pageSize,this.$state);
                // });
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
                gridApi.selection.on.rowSelectionChangedBatch(this.$scope, this.batchSelectChange);
            }
        }

        this.$scope.query = this.query;
        this.query();
    }

    localHistory():void{
        super.localHistory(this.$state);
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 加载数据
     */
    loadData(queryTerms: ReceivableCloseQueryTerms, skip: number, count: number): void {
        this.receivableService.receivablelist(this.orderBy.toString(), this.asc, queryTerms.clientName, queryTerms.settle, this.settleid, queryTerms.businessaffairsid, queryTerms.starttime,
            queryTerms.endtime, queryTerms.carcode, queryTerms.contractnumber, queryTerms.receiptstatus, queryTerms.settlestatus, queryTerms.origin, queryTerms.destination, this.parentid,
            this.isaccountenroute,"", queryTerms.feeType, true, "", queryTerms.orderStatus, "","", queryTerms.realStartTime,queryTerms.realEndTime,skip, count).then((res) => {
                // this.$scope.gridOptions.totalItems = res.data.total;
                this.$scope.gridOptions.data = res.data.data;

                /**
                 * 设置列表高度
                 */
                
                this.$scope.heightA = ((res.data.data.length)*39)+96;
                this.selectCheckBox(this.$scope.gridOptions.data);

                var currentPage = this.paginationOptions.currentPage;
                var totalPages = this.gridApi.pagination.getTotalPages();
                if (totalPages < currentPage) { this.$scope.gridOptions.paginationCurrentPage = 1; };
                this.$scope.querying = false;
            }, (error) => {
                this.$scope.querying = false;
            });
     
    }

    getListCount():void{
        /**应收合计 */
        this.totalReceivable();
         this.receivableService.receivablecount(this.$scope.queryTerms.clientName, this.$scope.queryTerms.settle, this.settleid, this.$scope.queryTerms.businessaffairsid, this.$scope.queryTerms.starttime,
            this.$scope.queryTerms.endtime, this.$scope.queryTerms.carcode, this.$scope.queryTerms.contractnumber, this.$scope.queryTerms.receiptstatus, this.$scope.queryTerms.settlestatus,this.$scope.queryTerms.origin, this.$scope.queryTerms.destination, this.parentid,
            this.isaccountenroute,"", this.$scope.queryTerms.feeType, true, "", this.$scope.queryTerms.orderStatus,"","",this.$scope.queryTerms.realStartTime,this.$scope.queryTerms.realEndTime).then(res=>{
            this.$scope.gridOptions.totalItems = res.data.extData;
            console.log(this.$scope.gridOptions.totalItems)
        })
    }

    /**
     * 所有状态枚举下拉
     */
    loadValueDropDown(): void {
        this.$scope.receiptPriceStatusList = this.valueService.getReceiptStatusList().data;
        this.$scope.settleTypeList = this.valueService.getSettleStatusList().data;
        this.$scope.feeTypeList = this.valueService.getReceivableFeeTypeList().data;
        this.$scope.orderStatusList = this.valueService.getOrderStatusList().data;
    }

    /**
     * 商务专员下拉
     */
    loadBusinessOfficerDropDown(): void {
        this.employeeService.getbytype(CommissionerType.BusinessAffairs.toString(),0, -1).then(result => {
            this.$scope.businessOfficerList = result.data.data;
        });
    }

    /**
     * 排序事件触发
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<FinanceReceivableListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<FinanceReceivableListItemResponse>>) => {
        if (sortColumns.length == 0) {
            this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "receivableSettleBillCode": {
                    this.orderBy = 1;
                } break;
                case "receivableCode": {
                    this.orderBy = 2;
                } break;
                case "feeType": {
                    this.orderBy = 3;
                } break;
                case "receivableSummary": {
                    this.orderBy = 4;
                } break;
                case "client": {
                    this.orderBy = 5;
                } break;
                case "settle": {
                    this.orderBy = 6;
                } break;
                case "originAddress": {
                    this.orderBy = 7;
                } break;
                case "realDeliveryTime": {
                    this.orderBy = 8;
                } break;
                case "goodsName": {
                    this.orderBy = 9;
                } break;
                case "receivableTotalPrice": {
                    this.orderBy = 10;
                } break;
                case "contractNumber": {
                    this.orderBy = 11;
                } break;
                case "carCode": {
                    this.orderBy = 12;
                } break;
                case "settleStatus": {
                    this.orderBy = 13;
                } break;
                case "receiptStatus": {
                    this.orderBy = 14;
                } break;
            }

            this.asc = sortItem.sort.direction == "asc";
            this.reload();

        }
    }

    /**
     * 单选事件
     */
    selectChange = (row: uiGrid.IGridRowOf<FinanceReceivableListItemResponse>) => {
        if (this.lockSelect) {
            return;
        }
        if (row.isSelected == true) {
            this.$scope.receivableIdList.forEach((item, index) => {
                if (row.entity.receivableCode == item.code) {
                    this.$scope.receivableIdList.splice(index, 1)
                }
            })
            this.$scope.receivableIdList.push({
                settleId:row.entity.settleId,
                id: row.entity.id,
                code: row.entity.receivableCode,
                client: row.entity.client,
                settle: row.entity.settle,
                settleStatus: row.entity.settleStatus,
                receivableTotalPrice: row.entity.receivableTotalPrice
            });

        } else {
            this.$scope.receivableIdList.forEach((item, index) => {
                if (row.entity.receivableCode == item.code) {
                    this.$scope.receivableIdList.splice(index, 1)
                };
            })
        }
    }

    /**
     * 全选事件
     */
    batchSelectChange = (rows: Array<uiGrid.IGridRowOf<FinanceReceivableListItemResponse>>) => {
        if (this.lockSelect) {
            return;
        }

        rows.forEach((item, index) => {
            if (item.isSelected) {
                this.$scope.receivableIdList.push({
                    settleId:item.entity.settleId,
                    id: item.entity.id,
                    code: item.entity.receivableCode,
                    client: item.entity.client,
                    settle: item.entity.settle,
                    settleStatus: item.entity.settleStatus,
                    receivableTotalPrice: item.entity.receivableTotalPrice
                })
            } else {
                rows.forEach((item, index) => {
                    this.$scope.receivableIdList.forEach((items, indexs) => {
                        if (item.entity.receivableCode === items.code) {
                            this.$scope.receivableIdList.splice(indexs, 1)
                        };
                    });
                });
            }
        })
    }

    /**
     * 获取应收合计
     */
    totalReceivable = () => {
        this.receivableService.getTotalReceivable(this.$scope.queryTerms.clientName, this.$scope.queryTerms.settle, this.settleid, this.$scope.queryTerms.businessaffairsid, this.$scope.queryTerms.starttime,
            this.$scope.queryTerms.endtime, this.$scope.queryTerms.carcode, this.$scope.queryTerms.contractnumber, this.$scope.queryTerms.receiptstatus, this.$scope.queryTerms.settlestatus, this.$scope.queryTerms.origin,
            this.$scope.queryTerms.destination, this.parentid, this.isaccountenroute, "", this.$scope.queryTerms.feeType, true, "", this.$scope.queryTerms.orderStatus, "","",this.$scope.queryTerms.realStartTime,
            this.$scope.queryTerms.realEndTime).then((res) => {
                this.$scope.totalReceivable = res.data.totalReceivable;
            }, (rej) => { })
    }

    /**
     * 翻页后选中
     */
    selectCheckBox = (data:string | FinanceReceivableListItemResponse[]) => {
        if (this.$scope.receivableIdList.length <= 0) { return };
        this.lockSelect = true;
        if (this.isFinanceReceivableListItemResponse(data)) {
            data.forEach((item, index) => {
                this.$scope.receivableIdList.forEach((itemS, indexS) => {
                    if (item.id == itemS.id) {
                        this.$timeout(() => {
                            if (this.isFinanceReceivableListItemResponse(data)) {
                                this.gridApi.selection.selectRow(data[index]);
                            }
                        })
                    }
                })
            });

        }
        this.lockSelect = false;

    }

    isFinanceReceivableListItemResponse(response: string | FinanceReceivableListItemResponse[]): response is FinanceReceivableListItemResponse[] {
        return (<FinanceReceivableListItemResponse[]>response).forEach !== undefined;
    }


    /**
    * 应收对账
    */
    receivableEdit = (CarrierOrderId: string, OrderId: string, OrderChildId: string, id: string, settleStatus: string, totalPrice: string, price: string, unit: string, receivableCode: string) => {
        this.$state.go("app.receivable.receivable_reconcile", { carrierOrderId: CarrierOrderId, orderId: OrderId, orderChildId: OrderChildId, Id: id, settleStatus: settleStatus, totalPrice: totalPrice, price: price, unit: unit, receivableCode: receivableCode, name: 'Edit' })
    }

    /**
    *清空费用编号
    */
    empty = () => {
        this.$ngBootbox.confirm("确定清空所有选中项吗").then(() => {
            this.$scope.receivableIdList = [];
            this.gridApi.selection.clearSelectedRows();
        }, () => { return });
    }

    /**
    *审核退回
    */
    auditBack = () => {
        if (this.$scope.receivableIdList.length < 1) {
            this.$ngBootbox.alert("请选择至少一项");
            return;
        } else if (this.$scope.receivableIdList.length > 1) {
            this.$ngBootbox.alert("只能选择一项");
            return;
        }
        var yes = true;
        this.$scope.receivableIdList.forEach((item, index) => {
            if (item.settleStatus != "办理") {
                yes = false;
                return false;
            };
        });
        if (!yes) { this.$ngBootbox.alert("结算状态为办理才能审核"); return; }
        this.$ngBootbox.confirm("确定审核退回吗？").then(() => {
            this.receivableService.returnReceivable(this.$scope.receivableIdList[0].id).then((res) => {
                this.$scope.receivableIdList = [];
                this.gridApi.selection.clearSelectedRows();
                this.query();
                this.totalReceivable();
            }, (rej) => { })
        }, () => { return })
        
    }


    //审核通过
    auditPass = () => {
        if (this.$scope.receivableIdList.length < 1) {
            this.$ngBootbox.alert("请选择至少一项");
            return;
        }
        var yes = true;
        var isTotal = true;
        this.$scope.receivableIdList.forEach((item, index) => {
            if (item.settleStatus != "办理") {
                yes = false;
                return false;
            };
            if( item.receivableTotalPrice==="" || item.receivableTotalPrice == null ){
                isTotal=false;
                return false;
            }
        });
        if (!yes) { 
            this.$ngBootbox.alert("结算状态为办理才能审核"); 
            return; 
        };
        if(!isTotal) {
            this.$ngBootbox.alert("有应收总价的才能审核"); 
            return;
        }
        var idArr = [];
        this.$scope.receivableIdList.forEach((item) => {
            idArr.push(item.id);
        });

        this.$ngBootbox.confirm('确定审核通过吗?').then(() => {
            this.receivableService.audited(idArr.join(",")).then((res) => {
                this.$scope.receivableIdList = [];
                this.gridApi.selection.clearSelectedRows();
                this.query();
                this.totalReceivable();
            }, (rej) => { });
        }, () => { return });
        
    };


    /**
    *生成应收账单
    */
    receivableChecking = () => {
        let arr = [];
        let idArr = [];
        let yes = true;

     
        let temp_settle='';
        let settle_dis=true;
        if (this.$scope.receivableIdList.length < 1) {
            this.$ngBootbox.alert("请选择一项");
            return;
        };
       
        this.$scope.receivableIdList.forEach((item, index) => {
            arr.push(item.code);
            idArr.push(item.id);
            if(index===0){
               
                temp_settle=item.settleId;
            }else{
               
                if(temp_settle!==item.settleId){
                    settle_dis=false;
                }
            }
    
            if (item.settleStatus != "已审核") {
                yes = false;
                return false;
            };
        });

        if (!yes) { this.$ngBootbox.alert("结算状态为已审核才能生成账单"); return; }
        if (!settle_dis) { this.$ngBootbox.alert("客户单位必须一致且结算单位必须一致"); return; };
        this.$state.go("app.receivable.receivableCloseBill", { id: arr.join(","), name: idArr.join(",") });
    }

    /**
    *新增应收单
    */
    receivableAdd = () => {
        let codeArr = [];
        let idArr = [];
        
      
        let temp_settle='';
        let settle_dis=true;
        let yes = true;
        if (this.$scope.receivableIdList.length < 1) {
            this.$ngBootbox.alert("请选择一项");
            return;
        };
        this.$scope.receivableIdList.forEach((item, index) => {
            if(index===0){
                
                temp_settle=item.settleId;
            }else{
               
                if(temp_settle!==item.settleId){
                    settle_dis=false;
                }
            }
            codeArr.push(item.code);
            idArr.push(item.id);
        });
        if (!yes) { this.$ngBootbox.alert("结算状态为已审核才能生成应收单"); return; };
        if (!settle_dis) { this.$ngBootbox.alert("客户单位必须一致且结算单位必须一致"); return; };
        this.$state.go("app.receivable.receivableCloseAdd", { id: codeArr.join(','), code: idArr.join(",") });
    };

    /**
    *取消审核
    */
    cancel = (id: string) => {
        this.$ngBootbox.confirm("确定取消审核吗?").then(() => {
            this.receivableService.returnaudited(id).then((res) => {
                this.query();
                this.totalReceivable();
            }, (rej) => { })
        }, () => { return });

        this.$timeout(()=>{
            this.$scope.receivableIdList = [];
            this.gridApi.selection.clearSelectedRows();
        })
        
    }

    /**
    *报表
    */
   
    /**
    *导出
    */
    exportFunc=()=>{
        if(this.$scope.gridOptions.totalItems>60000){
            this.$ngBootbox.alert('导出数据不可超过6万条');
            return;
        }else{
            this.exportService.exportReceivable(this.orderBy,this.asc,this.queryTerms.clientName,this.queryTerms.settle,
                this.settleid,this.queryTerms.businessaffairsid,this.queryTerms.starttime,this.queryTerms.endtime,
                this.queryTerms.carcode,this.queryTerms.contractnumber,this.queryTerms.receiptstatus,this.queryTerms.settlestatus,this.queryTerms.origin,
                this.queryTerms.destination,this.parentid,this.isaccountenroute,"",this.queryTerms.feeType,true,"",this.queryTerms.orderStatus,"","",false,
                this.$scope.queryTerms.realStartTime,this.$scope.queryTerms.realEndTime)
        }
        
    }
    

    /**
    *删除选中订单
    */
    delId = (arg: any,data:string | FinanceReceivableListItemResponse[]) => {
        this.$scope.receivableIdList.forEach((item, index) => {
            if (arg === item.code) {
                this.$scope.receivableIdList.splice(index, 1);
                if (this.isFinanceReceivableListItemResponse(data)) {
                    data.forEach((items, indexs) => {
                        if (item.code == items.receivableCode) {
                            this.gridApi.selection.unSelectRow(items);
                        }
                    })
                }

            }
        })
    }

}

angular.module("tms").controller("receivableCloseController", ['$scope',
    'receivableService',
    'valueService',
    'orderService',
    '$ngBootbox',
    '$state',
    'authorizationService',
    'employeeService',
    '$timeout',
    'exportService',
    '$http',
    "$location",
     ReceivableCloseController]);